package com.gxc.recursion;

import java.util.ArrayList;
import java.util.List;

/**
 * 括号生成
 * 数字 n 代表生成括号的对数，请你设计一个函数，用于能够生成所有可能的并且 有效的 括号组合。
 */
public class GenerateParenthesis {

    public List<String> generateParenthesis(int n) {
        List<String> res = new ArrayList<>();
        backtrack(0, 0, n , res, new StringBuilder());
        return res;
    }

    public void backtrack( int open, int close, int max, List<String> res, StringBuilder cur) {
        if (cur.length() == max * 2) {
            res.add(cur.toString());
            return;
        }
        if (open < max) {
            cur.append('(');
            backtrack(open+1, close, max , res, cur);
            cur.deleteCharAt(cur.length() - 1);
        }
        if (close < open) {
            cur.append(')');
            backtrack(open, close+1, max , res, cur);
            cur.deleteCharAt(cur.length() - 1);
        }
    }
}
